<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="车辆名称" size="small">
            <el-input v-model="searchForm.carName"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="车牌" size="small">
            <el-input v-model="searchForm.carBrand"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="500px">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="110px">
          <el-form-item prop="carName" label="车辆名称" size="small">
            <el-input type="text" v-model="teamRow.carName"></el-input>
          </el-form-item>
          <el-form-item label="车牌" size="small">
            <el-input type="text" v-model="teamRow.carBrand"></el-input>
          </el-form-item>
          <el-form-item label="型号" size="small">
            <el-input type="text" v-model="teamRow.model"></el-input>
          </el-form-item>
          <el-form-item label="车辆识别代号" size="small">
            <el-input type="text" v-model="teamRow.carIdentificationNumber"></el-input>
          </el-form-item>
          <el-form-item label="发动机号" size="small">
            <el-input type="text" v-model="teamRow.engineNumber"></el-input>
          </el-form-item>
          <el-form-item label="车架号" size="small">
            <el-input type="text" v-model="teamRow.frameNumber"></el-input>
          </el-form-item>
          <el-form-item label="结构特点" size="small">
            <el-input type="text" v-model="teamRow.structuralFeatures"></el-input>
          </el-form-item>
          <el-form-item label="保险一" size="small">
            <el-input type="text" v-model="teamRow.insurance"></el-input>
          </el-form-item>
          <el-form-item label="投保公司一" size="small">
            <el-input type="text" v-model="teamRow.insuranceCompany"></el-input>
          </el-form-item>
          <el-form-item label="保险起止时间一" size="small">
            <el-date-picker
              v-model="teamRow.insuranceStartEnd"
              type="daterange"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="保险二" size="small">
            <el-input type="text" v-model="teamRow.insuranceTwo"></el-input>
          </el-form-item>
          <el-form-item label="投保公司二" size="small">
            <el-input type="text" v-model="teamRow.insuranceCompanyTwo"></el-input>
          </el-form-item>
          <el-form-item label="保险起止时间二" size="small">
            <el-date-picker
              v-model="teamRow.insuranceStartEndTwo"
              type="daterange"
              value-format="timestamp"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="车身照片前" size="small">
            <input type="file" ref='file' accept="image/*" @change="getFile($event)">
          </el-form-item>
          <el-form-item label="车身照片后" size="small">
            <input type="file" ref='file1' accept="image/*" @change="getFile1($event)">
          </el-form-item>
          <el-form-item label="备注说明" size="small">
            <el-input type="textarea" v-model="teamRow.remark"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      @openVisible="openVisible"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.carId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-popover
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="imgMsg.label" :visible.sync="imgVisible" width="600px">
      <img class="img-dialog" :src="imgMsg.src" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import { getList, addInformation, selectInformation, deleteInformation, updateInformation } from '@/api/vehicleinfo'
  import myTable from '@/components/myTable'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const insuranceStartEnd = {
    props: ['colConfig'],
    filters: {
      formatstart(time) {
        if (time) {
          var date = new Date(parseInt(time.split(',')[0]))
          return formatDate(date, 'yyyy-MM-dd')
        }
      },
      formatend(time) {
        if (time) {
          var date = new Date(parseInt(time.split(',')[1]))
          return formatDate(date, 'yyyy-MM-dd')
        }
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatstart }} - {{ scope.row[colConfig.prop] | formatend }}
      </span>
  </el-table-column>
  `
  }

  const img = {
    props: ['colConfig'],
    methods: {
      openVisible(label, src) {
        const msg = {
          label: label,
          src: src
        }
        this.$emit('openImgVisible', msg)
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        <div v-if="colConfig.type==='img'">
          <a v-if="scope.row[colConfig.prop]" @click="openVisible(colConfig.label,scope.row[colConfig.prop])">查看
          </a>
        </div>
        <div v-else>
          <a v-if="scope.row[colConfig.prop]" target="_blank" :href="GLOBAL.filePathUrl+ encodeURI(scope.row[colConfig.prop])">下载</a>
        </div>
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'carName', label: '车辆', width: '150', fixed: true },
          { prop: 'carBrand', label: '车牌', width: '150' },
          { prop: 'model', label: '型号', width: '150' },
          { prop: 'carIdentificationNumber', label: '车辆识别代号', width: '150' },
          { prop: 'engineNumber', label: '发动机号', width: '150' },
          { prop: 'frameNumber', label: '车架号', width: '150' },
          { prop: 'structuralFeatures', label: '结构特点', width: '150' },
          { prop: 'insurance', label: '保险一', width: '150' },
          { prop: 'insuranceCompany', label: '投保公司一', width: '150' },
          { prop: 'insuranceStartEnd', label: '保险起止时间一', width: '180', component: insuranceStartEnd },
          { prop: 'insuranceTwo', label: '保险二', width: '150' },
          { prop: 'insuranceCompanyTwo', label: '投保公司二', width: '150' },
          { prop: 'insuranceStartEndTwo', label: '保险起止时间二', width: '180', component: insuranceStartEnd },
          { prop: 'bodyPhotoFront', label: '车身照片前', width: '150', type: 'img', component: img },
          { prop: 'bodyPhotoAfter', label: '车身照片后', width: '150', type: 'img', component: img },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        professions: [],
        typeNames: [],
        listLoading: true,
        dialogTitle: '新增车辆信息表',
        dialogType: 0,
        teamRow: {
          insuranceStartEnd: []
        },
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        pca: pca,
        rules: {
          carName: [
            { required: true, message: '请输入车辆名称', trigger: 'change' }
          ]
        },
        visible: false,
        imgVisible: false,
        imgMsg: {}
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增车辆信息表'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        if (this.$refs.file1) {
          this.$refs.file1.value = ''
        }
      },
      editTeam(carId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改车辆信息表'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 0
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        if (this.$refs.file1) {
          this.$refs.file1.value = ''
        }
        const params = {
          carId: carId
        }
        selectInformation(params).then(response => {
          this.teamRow = Object.assign({}, this.teamRow, response.responseBody)
          this.teamRow.insuranceStartEnd = this.teamRow.insuranceStartEnd.split(',')
          this.teamRow.insuranceStartEndTwo = this.teamRow.insuranceStartEndTwo.split(',')
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('carName', this.teamRow.carName)
        params.append('carBrand', this.teamRow.carBrand || '')
        params.append('model', this.teamRow.model || '')
        params.append('carIdentificationNumber', this.teamRow.carIdentificationNumber || '')
        params.append('engineNumber', this.teamRow.engineNumber || '')
        params.append('frameNumber', this.teamRow.frameNumber || '')
        params.append('structuralFeatures', this.teamRow.structuralFeatures || '')
        params.append('insurance', this.teamRow.insurance || '')
        params.append('insuranceCompany', this.teamRow.insuranceCompany || '')
        if (this.teamRow.insuranceStartEnd) {
          params.append('insuranceStartEnd', this.teamRow.insuranceStartEnd.join(','))
        }
        params.append('insuranceTwo', this.teamRow.insuranceTwo || '')
        params.append('insuranceCompanyTwo', this.teamRow.insuranceCompanyTwo || '')
        if (this.teamRow.insuranceStartEndTwo) {
          params.append('insuranceStartEndTwo', this.teamRow.insuranceStartEndTwo.join(','))
        }
        params.append('file', this.teamRow.file)
        params.append('file1', this.teamRow.file1)
        params.append('remark', this.teamRow.remark || '')
        if (!this.dialogType) {
          params.append('carId', this.teamRow.carId)
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              addInformation(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateInformation(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        console.log(this.$refs[`popover-${scope.$index}`])
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          carId: scope.row.carId,
          isDel: 1
        }
        deleteInformation(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      selectGet(vId) {
        let obj = {}
        obj = this.GLOBAL.subjectionDepartmentList.find((item) => {
          return item.value === vId // 筛选出匹配数据
        })
        this.teamRow.departmentName = obj.label
      },
      getFile(event) {
        this.teamRow.file = event.target.files[0]
      },
      getFile1(event) {
        this.teamRow.file1 = event.target.files[0]
      },
      openVisible(msg) {
        this.imgVisible = true
        this.imgMsg = msg
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
    .dialog-line {
      width: 330px;
    }
    .img-dialog {
      max-width: 540px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
